package com.jiao.databinding3.baseobservable;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.Observable;

import com.jiao.databinding3.BR;
import com.jiao.databinding3.R;
import com.jiao.databinding3.databinding.ActivityMain1Binding;

import java.util.Random;

public class MainActivity1 extends AppCompatActivity {

    String TAG ="===";
    private Goods goods;

    private ActivityMain1Binding activityMain3Binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMain3Binding = DataBindingUtil.setContentView(this, R.layout.activity_main1);
        goods = new Goods("code", "hi", 24);
        activityMain3Binding.setGoods(goods);
        activityMain3Binding.setGoodsHandler(new GoodsHandler());
/*
* 实现了 Observable 接口的类允许注册一个监听器，
* 当可观察对象的属性更改时就会通知这个监听器，此时就需要用到 OnPropertyChangedCallback
* */
        goods.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                if (propertyId == BR.name) {
                    Log.e(TAG, "BR.name"+goods.name);
                } else if (propertyId == BR.details) {
                    Log.e(TAG, "BR.details"+goods.getDetails());
                } else if (propertyId == BR._all) {
                    Log.e(TAG, "BR._all");
                } else {
                    Log.e(TAG, "未知");
                }
            }
        });
    }

    public class GoodsHandler {

        public void changeGoodsName() {
            goods.setName("code" + new Random().nextInt(100));
            goods.setPrice(new Random().nextInt(100));
        }

        public void changeGoodsDetails() {
            goods.setDetails("hi222");
            goods.setPrice(new Random().nextInt(100));
        }

    }
}
